package com.uzai.console.service.takebal.impl;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.uzai.common.entity.User;
import com.uzai.common.exception.BusinessException;
import com.uzai.common.result.ResponseCode;
import com.uzai.console.common.utils.DateUtil;
import com.uzai.console.constant.CacheKey;
import com.uzai.console.dto.takebal.takebalblacklist.TakeBalBlacklistIdDto;
import com.uzai.console.dto.takebal.takebalblacklist.TakeBalBlacklistIdListDto;
import com.uzai.console.dto.takebal.takebalblacklist.TakeBalBlacklistInfoDto;
import com.uzai.console.dto.takebal.takebalblacklist.TakeBalBlacklistQuery;
import com.uzai.console.entity.TakeBalBlacklist;
import com.uzai.console.mapper.TakeBalBlacklistMapper;
import com.uzai.console.service.device.DeviceService;
import com.uzai.console.service.takebal.TakeBalBlacklistService;
import com.uzai.console.service.user.UserService;
import com.uzai.console.vo.takebal.takebalblacklist.TakeBalBlacklistInfoVo;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author liuqi
 * @date 2021年08月23日 20:25
 */
@Service
public class TakeBalBlacklistServiceImpl implements TakeBalBlacklistService {

    Logger logger = LoggerFactory.getLogger(TakeBalBlacklistServiceImpl.class);

    @Autowired
    private TakeBalBlacklistMapper takeBalBlacklistMapper;
    @Autowired
    private DeviceService deviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询提现黑名单列表
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param takeBalBlacklistQuery
     * @return null
     */
    public Page<TakeBalBlacklistInfoVo> findTakeBalBlacklistList(TakeBalBlacklistQuery takeBalBlacklistQuery){
        //新建返回到页面的LIST对象
        List<TakeBalBlacklistInfoVo> takeBalBlacklistPageVoList = new ArrayList<>();

        //执行分页查询对象
        Page<TakeBalBlacklist> page = new Page<>();
        takeBalBlacklistQuery.convert(page);
        ArrayList<TakeBalBlacklist> takeBalBlacklistList =  takeBalBlacklistMapper.findByList(page, takeBalBlacklistQuery);
        if(takeBalBlacklistList != null && takeBalBlacklistList.size() > 0){
            for (TakeBalBlacklist takeBalBlacklist : takeBalBlacklistList){
                TakeBalBlacklistInfoVo takeBalBlacklistPageVo = new TakeBalBlacklistInfoVo();
                BeanUtils.copyProperties(takeBalBlacklist, takeBalBlacklistPageVo);
                takeBalBlacklistPageVoList.add(takeBalBlacklistPageVo);
            }
        }
        //返回到页面分页对象
        Page<TakeBalBlacklistInfoVo> pageVo = new Page<>();
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(takeBalBlacklistPageVoList);
        //将分页信息复制到返回到页面的分页MO当中
        return pageVo;
    }

    /**
     * 添加提现黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param takeBalBlacklistInfoDto
     * @return null
     */
    @Transactional
    public void addTakeBalBlacklist(TakeBalBlacklistInfoDto takeBalBlacklistInfoDto){

        if(takeBalBlacklistInfoDto.getUserId() == null && StringUtils.isBlank(takeBalBlacklistInfoDto.getAlipayAccount())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员ID和支付宝账号账户必须输入一个");
        }

        //如果会员id不为空，则需要此会员id是否存在
        if(takeBalBlacklistInfoDto.getUserId() != null){
            TakeBalBlacklist takeBalBlacklist_old = takeBalBlacklistMapper.selectByUserId(takeBalBlacklistInfoDto.getUserId(), takeBalBlacklistInfoDto.getMerId());
            if(takeBalBlacklist_old != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "会员ID已经存在");
            }
        }

        //如果会员id不为空，则需要次会员id是否存在
        if(StringUtils.isNotBlank(takeBalBlacklistInfoDto.getAlipayAccount())){
            TakeBalBlacklist takeBalBlacklist_old = takeBalBlacklistMapper.selectByAlipayAccount(takeBalBlacklistInfoDto.getAlipayAccount(), takeBalBlacklistInfoDto.getMerId());
            if(takeBalBlacklist_old != null){
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "支付宝账号已经存在");
            }
        }

        TakeBalBlacklist takeBalBlacklist = new TakeBalBlacklist();
        BeanUtils.copyProperties(takeBalBlacklistInfoDto, takeBalBlacklist);

        Integer now = DateUtil.getNowTime();
        Long id = IdWorker.getId();
        takeBalBlacklist.setId(id);
        takeBalBlacklist.setCreateTime(now);
        takeBalBlacklist.setUpdateTime(now);

        //通过微信ID查询用户信息
        if(takeBalBlacklistInfoDto.getUserId() != null){
            User user = userService.findUserInfo(takeBalBlacklistInfoDto.getUserId(), null, takeBalBlacklistInfoDto.getMerId());
            if(user != null ){
                takeBalBlacklist.setNickName(user.getNickName());
                takeBalBlacklist.setDeviceType(user.getDeviceType());
            }else{
                throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员id不存在");
            }
        }
        //默认为个人微信黑名单
        takeBalBlacklistMapper.insert(takeBalBlacklist);

        //AOP切面，封装操作日志内容
        String aspectOperatorLog = "添加提现黑名单。会员id:"+takeBalBlacklistInfoDto.getUserId() +";支付宝账号:" + takeBalBlacklistInfoDto.getAlipayAccount() ;
        takeBalBlacklistInfoDto.setAspectOperatorLog(aspectOperatorLog);

    }

    /**
     * 修改提现黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param takeBalBlacklistInfoDto
     * @return null
     */
    @Transactional
    public void updateTakeBalBlacklist(TakeBalBlacklistInfoDto takeBalBlacklistInfoDto){

        if(takeBalBlacklistInfoDto.getUserId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入会员ID");
        }

        if(StringUtils.isBlank(takeBalBlacklistInfoDto.getAlipayAccount())){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "请输入支付宝账号");
        }

        TakeBalBlacklist takeBalBlacklist = takeBalBlacklistMapper.selectById(takeBalBlacklistInfoDto.getId(), takeBalBlacklistInfoDto.getMerId());

        if(takeBalBlacklist == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现黑名单不存在");
        }

        Integer now = DateUtil.getNowTime();
        takeBalBlacklist.setUpdateTime(now);
        takeBalBlacklist.setUserId(takeBalBlacklistInfoDto.getUserId());
        //通过微信ID查询用户信息
        User user = userService.findUserInfo(takeBalBlacklistInfoDto.getUserId(), takeBalBlacklist.getDeviceType(), takeBalBlacklistInfoDto.getMerId());
        if(user != null ){
            takeBalBlacklist.setNickName(user.getNickName());
        }else{
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该会员id不存在");
        }
        takeBalBlacklistMapper.updateById(takeBalBlacklist);
    }

    /**
     * 移除黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param takeBalBlacklistIdDto
     * @return null
     */
    @Transactional
    public void deleteTakeBalBlacklist(TakeBalBlacklistIdDto takeBalBlacklistIdDto){

        if(takeBalBlacklistIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        TakeBalBlacklist takeBalBlacklist = takeBalBlacklistMapper.selectById(takeBalBlacklistIdDto.getId(), takeBalBlacklistIdDto.getMerId());

        if(takeBalBlacklist == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "此提现黑名单不存在");
        }

        //删除提现黑名单
        takeBalBlacklistMapper.deleteById(takeBalBlacklistIdDto.getId(), takeBalBlacklistIdDto.getMerId());

        //AOP切面，封装操作日志内容
        String aspectOperatorLog = "移除提现黑名单。会员id:"+takeBalBlacklist.getUserId() +";支付宝账号:" + takeBalBlacklist.getAlipayAccount() ;
        takeBalBlacklistIdDto.setAspectOperatorLog(aspectOperatorLog);

    }

    /**
     * 批量删除
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param takeBalBlacklistIdListDto
     * @return null
     */
    public void batchDeleteTakeBalBlacklist(TakeBalBlacklistIdListDto takeBalBlacklistIdListDto){
        List<Long> idList = takeBalBlacklistIdListDto.getIdList();
        if(idList == null || idList.size() == 0){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"请选择输入批量删除记录");
        }

        //根据机器人列表查询需要增加限制时间
        if(idList.size() >= 100){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"批量删除总数量不能超过100个");
        }

        String val = (String) redisTemplate.opsForValue().get(String.format(CacheKey.BATCH_DELETE_TAKEBAL_BLCKLIST_PRV, takeBalBlacklistIdListDto.getMerId()));
        if (StringUtils.isNotBlank(val)){
            throw new BusinessException(ResponseCode.BUSINESS_EXCEPTION,"2分钟只允许一次批量操作");
        }
        //往reids插入本次下载，允许5分钟下载一次，避免频繁提交
        redisTemplate.opsForValue().set(String.format(CacheKey.BATCH_DELETE_TAKEBAL_BLCKLIST_PRV,takeBalBlacklistIdListDto.getMerId()),takeBalBlacklistIdListDto.getMerId()+"",2, TimeUnit.MINUTES);


        for (Long id : idList) {
            try {
                TakeBalBlacklistIdDto takeBalBlacklistIdDto = new TakeBalBlacklistIdDto();
                takeBalBlacklistIdDto.setMerId(takeBalBlacklistIdListDto.getMerId());
                takeBalBlacklistIdDto.setId(id);
                deleteTakeBalBlacklist(takeBalBlacklistIdDto);
            }catch (Exception e){
                logger.error("批量删除删除提现黑名称出错。error={}", e.getMessage());
            }
        }
    }

    /**
     * 查询提现黑名单
     * @author liuqi
     * @date 2021/8/13 11:38
     * @param takeBalBlacklistIdDto
     * @return null
     */
    public TakeBalBlacklistInfoVo findTakeBalBlacklistInfo(TakeBalBlacklistIdDto takeBalBlacklistIdDto){
        if(takeBalBlacklistIdDto.getId() == null){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "id不能为空");
        }

        TakeBalBlacklist takeBalBlacklist = takeBalBlacklistMapper.selectById(takeBalBlacklistIdDto.getId(), takeBalBlacklistIdDto.getMerId());

        if(takeBalBlacklist == null ){
            throw  new BusinessException(ResponseCode.BUSINESS_EXCEPTION, "该提现黑名单不存在");
        }

        TakeBalBlacklistInfoVo takeBalBlacklistInfoVo = new TakeBalBlacklistInfoVo();
        BeanUtils.copyProperties(takeBalBlacklist, takeBalBlacklistInfoVo);
        return takeBalBlacklistInfoVo;
    }

}
